package com.shu.project.controller;

import com.shu.framework.constant.UserConstants;
import com.shu.framework.enums.CodeMsg;
import com.shu.framework.redis.RedisService;
import com.shu.framework.redis.SessionKey;
import com.shu.framework.result.Result;
import com.shu.framework.utils.StringUtils;
import com.shu.project.model.User;
import com.shu.project.service.IGoodsService;
import com.shu.project.service.IUserService;
import com.shu.project.vo.GoodsVo;
import com.shu.project.vo.LoginVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    private static final Logger log = LoggerFactory.getLogger(GoodsController.class);
    @Autowired
    IUserService userService;
    @Autowired
    IGoodsService goodsService;
    @RequestMapping("/to_list")
    public String toList( Model model,User user){
        if (StringUtils.isNull(user)){return "login";}
        model.addAttribute("user",user);
        List<GoodsVo> goodsVos = goodsService.queryGoodsAll();
        log.info(goodsVos.toString());
        model.addAttribute("goodsVoList",goodsVos);
        return "goods_list";
    }
    @RequestMapping("/to_detail/{goodsId}")
    public String toDetail(Model model, User user, @PathVariable("goodsId")Long goodsId){
        if (StringUtils.isNull(user)){return "login";}
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.queryGoodsVoById(goodsId);
        if (StringUtils.isNull(goodsVo.getStartDate()) && StringUtils.isNull(goodsVo.getEndDate())){
            return "error";
        }
        model.addAttribute("goodsVo",goodsVo);
        long startAt =goodsVo.getStartDate().getTime();
        long endAt =goodsVo.getEndDate().getTime();
        long now =System.currentTimeMillis();

        int seckillStatus=0;
        int remainSeconds=0;
        if(startAt>now){//秒杀未开始
            seckillStatus=0;
            remainSeconds=(int)((startAt-now)/1000);
        }else if (now>endAt){//秒杀结束
            seckillStatus=2;
            remainSeconds=-1;
        }else {//进行中
            seckillStatus=1;
            remainSeconds=0;
        }
        model.addAttribute("seckillStatus",seckillStatus);
        model.addAttribute("remainSeconds",remainSeconds);

        return "goods_detail";
    }

}
